/**
 * Created by Administrator on 2015/1/20.
 */
define([""],function(){
	var G = {};
	var AJAX_URL = WXB.URLS.api;
	var AJAX_TIMEOUT = WXB.URLS.AJAX_TIMEOUT;
	var UID = (function(){
		var uid = 1;
		function set(id){
			if(typeof id !== "undefined") uid = id;
		}
		function get(){
			return uid++;
		}
		function refresh(){
			uid = 1;
		}
		return{
			get : get,
			set : set,
			refresh : refresh
		}
	})();
	//一级菜单最大个数
	var MAX_MENU_COUNT = 3;
	//二级菜单最大个数
	var MAX_SUB_MENU_COUNT = 5;
	var GetMenuXHR = null;
	function setUp(){
		WXB.G.SwitchAccount.init(function(){
			var data = WXB.G.SwitchAccount.getData(0);
			var hash = WXB.G.SwitchAccount.getHash()
			refreshMenuView(hash);
			bindEvent();
		});
		WXB.G.SwitchAccount.on("change",function(data){
			refreshMenuView(data.hash);
		})
	}
	//切换公众号select时切换该帐号的详情信息, 不用发请求
	function refreshAccountDetail(data){
		data = data || {};
		var def = '<span style="font-style:italic; color:#adadad">（空）</span>';
		var hash = data.hash || def;
		var type = data.type || def;
		var token = data.token || def;
		var url = data.url || def;
		var aeskey = data.aeskey || def;
		var name = data.name || def;
		$("#account_type").html(type);
		$("#account_url").html(url);
		$("#account_token").html(token);
		$("#account_EncodingAESKey").html(aeskey);
		$("#account_name").html(name);
	}
	//切换公众号select时切换该帐号下的菜单数据 发请求
	function refreshMenuView(hash){
		if(!hash){
			console && console.log("缺省hash");
			return false;
		}
		var menuTbody = $("#menuTbody");
		var loadingLayer = $("#menuLoadingLayer");
		if(menuTbody.attr("data-loading") == true){
			console && console.log("亲，切换帐号别太频繁了...");
			//return false;
		}
		//uid回到始使值
		UID.refresh();
		if(GetMenuXHR && GetMenuXHR.abort){
			GetMenuXHR.abort();
		}
		menuTbody.html("");
		GetMenuXHR = ajaxGetMenu(hash,{
			loading : function(){
				loadingLayer.show();
				menuTbody.attr("data-loading",true);
			},
			removeLoading : function(){
				loadingLayer.hide();
				menuTbody.attr("data-loading",false);
			},
			success : function(res){
				var data = res;
				ininRender(res);
			},
			empty : function(res){
				var tr = '<tr class="ajaxGetMentListEmtyp"><td style="height:100px; line-height:100px; border-top:0 none; text-align:center">此帐号还没有创建按钮...</td></tr>';
				menuTbody.html(tr);
			},
			fail : function(res){
				var tr = '<tr class="fail"><td style="height:100px; line-height:100px; border-top:0 none; text-align:center">请求失败,请稍后重试...</td></tr>';
				menuTbody.html(tr);
			},
			timeout : function(){
				var tr = '<tr class="timeout"><td style="height:100px; line-height:100px; border-top:0 none; text-align:center">请求超时,请稍后重试...</td></tr>';
				menuTbody.html(tr);
			},
			error : function(){
				var tr = '<tr class="error"><td style="height:100px; line-height:100px; border-top:0 none; text-align:center">请求出错,请稍后重试...</td></tr>';
				menuTbody.html(tr);
			}
		});
	}
	//页面初使化时先ajax取得menu数据
	function ajaxGetMenu(hash,config){
		if(!hash){
			console && console.log("缺省hash");
			return false;
		}
		var config = config || {};
		var loading = config.loading || WXB.FN;
		var removeLoading = config.removeLoading || WXB.FN;
		var success = config.success || WXB.FN;
		var empty = config.empty || WXB.FN;
		var fail = config.fail || WXB.FN;
		var timeout = config.timeout || WXB.FN;
		var error = config.error || WXB.FN;
		$.ajax({
			url : WXB.URLS.api,
			type : "GET",
			dataType : "JSON",
			timeout : 120 * 1000, //2分钟超时
			data : { "action":"GetMenu", hash:hash },
			beforeSend : function(){
				loading();
			},
			success : function(res){
				removeLoading();
				if(res && res.length){
					success(res);
				}else if(res && res.length==0){
					empty(res);
				}else{
					fail(res);
				}
			},
			error : function(xhr,txt){
				removeLoading();
				if(txt == "timeout"){
					timeout();
				}else{
					error();
				}
			}
		})
	}
	function ininRender(data){
		var data = data || [];
		var phtml = "";
		var shtml = "";
		var wrap = $("#menuTbody");
		var findSubByPid = function(data,pid){
			if(!pid){
				console && console.log("invold pid");
				return false;
			}
			var result = [];
			for(var i in data){
				var d = data[i];
				var _pid = d["pid"];
				var id = d["id"];
				var name = d["name"];
				var type = d["type"];
				var code = d["code"];

				if(pid == _pid){
					result.push({pid:_pid, id:id, name:name, type:type, code:code});
				}
			}
			return result;
		};
		matchUID(data);
		for(var i=0; i<data.length; i++){
			var d = data[i];
			var pid = d.pid;
			var id = d.id;
			var name = d.name;
			var type = d.type;
			var code = d.code;
			var subMenuData = [];
			if(pid == "-1" || pid == ""){
				phtml = buildParentDom({
					id : id,
					name : name,
					type : type,
					code : code
				});
				wrap.append(phtml);
				subMenuData = findSubByPid(data,id);
				if(subMenuData.length){
					shtml = buildSubDom(subMenuData);
					$("#subMenuContainer-"+id).html(shtml);
				}
			}else{
				//shtml = buildSubDom({
				//	pid : pid,
				//	id : id,
				//	name : name,
				//	type : type,
				//	code : code
				//});
				//$("#subMenuContainer-"+pid).append(shtml)
			}
		}
		setTimeout(function(){
			watchParentSetAction();
		},0)
	}
	function bindEvent(){
		var container = $("#menuTbody");
		//添加一级菜单
		$("#addMenuBtn").on("click",function(e){
			onAddParentMenu();
			return false;
		})
		//添加子菜单
		container.on("click",".addSubMenuBtn",function(e){
			var target = $(e.currentTarget);
			var container = target.parent().next();
			var pid = container.attr("data-pid");
			onAddSubMenu(container,pid);
			return false;
		});
		//删除父菜单
		container.on("click",".removeParentMenuBtn",function(e){
			var target = $(e.currentTarget);
			var container = target.parents("tr");
			onRemoveParentMenu(container);
		});
		//删除子菜单
		container.on("click",".removeSubMenuBtn",function(e){
			var target = $(e.currentTarget);
			var container = target.parent();
			onRemoveSubMenu(container);
		});
		//设置菜单action
		container.on("click",".setParentActionBtn,.setSubActionBtn",function(e){
			var target = $(e.currentTarget);
			onSetAction(target);
		});
		//保存菜单结构
		$("#submitMenuDataBtn").on("click",function(e){
			onSubmitData();
		})
		container.on("blur",".textInp",function(e){
			var target = $(e.currentTarget);
			if(target.val()){
				target.siblings(".involName").remove();
			}
			return false;
		})
	}
	//添加一级菜单
	function onAddParentMenu(){
		var container = $("#menuTbody");
		var children = container.children();
		container.children(".ajaxGetMentListEmtyp").remove();
		if(children.length>=MAX_MENU_COUNT){
			alert("一级菜单个数不能超过"+MAX_MENU_COUNT+"个");
			return false;
		}
		var html = buildParentDom({
			id : UID.get(),
			name : "-1",
			type : "-1",
			code : "-1"
		})
		container.append(html);
		return false;
	}
	//添加子菜单
	function onAddSubMenu(container,pid){
		var subMenus = container.children();
		if(subMenus.length>=MAX_SUB_MENU_COUNT){
			alert("子菜单个数不能超过"+MAX_SUB_MENU_COUNT+"个");
			return false;
		}
		var html = buildSubDom([{
			pid : pid,
			id : UID.get(),
			name : "-1",
			type : "-1",
			code : "-1"
		}])
		container.append(html);
		container.prev().children(".setParentActionBtn").addClass("disabled");
	}
	//删除父菜单
	function onRemoveParentMenu(container){
		container.remove();
	}
	//删除子菜单
	function onRemoveSubMenu(container){
		var cparent = container.parent();
		var btn = cparent.prev().children(".setParentActionBtn");
		container.remove();
		if(cparent.children().length == 0){
			btn.removeClass("disabled");
		}else{
			btn.addClass("disabled");
		}
	}
	//设置菜单action
	function onSetAction(target){
		var cur_type = target.attr("data-type");
		var cur_code = target.attr("data-code");
		var _buildAction = function(data){
			var html = "";
			for(var i=0; i<data.length; i++){
				var d = data[i];
				var type = d["type"] || "-1";
				var name = d["name"] || "-1";
				var code = d["code"] || "-1";
				var custom = "-1"; //区分自定义动作或系统动作
				html += '<label class="radio-inline"><input type="radio" name="action" data-name="'+name+'" data-code="'+code+'" data-type="'+type+'" value="'+type+'" class="actionRadioInp"> '+name+'</label>';
			}
			return html;
		};
		_showDialog(function(){
			var dialogContainer = $("#gDialogContainer");
			var ajaxSuccess = dialogContainer.attr("data-ajaxsuccess");
			var init = dialogContainer.attr("data-init");
			dialogContainer.data("tarMenu",target.siblings(".textInp"));
			if(init !== "true"){ //只初始化一次  事件绑定要单独剖离出去  fuck!!!不能这么写
				//取消
				dialogContainer.on("click","#gDialog-colseBtn,#gDialog-cancelBtn",function(e){
					_closeDialog();
				})
				//保存
				dialogContainer.on("click","#gDialog-saveBtn",function(e){
					var tarMenu = $("#gDialogContainer").data("tarMenu");
					var container = $("#gDialog-body");
					//选取被选中的radio
					var selectedRadio = container.find("input:radio:checked");
					var type = selectedRadio.val();
					var name = selectedRadio.attr("data-name");
					var custom = selectedRadio.attr("data-custom");
					var code,customInpKeyword,customKeyVal,customInpLink,coustomLinkVal;
					//如果选中的是自定义菜单或自定义关键字
					if(custom == "keyword"){ //如果选中自定义关键字 则必须输入关键字
						customInpKeyword = $("#customInp-keyword");
						customKeyVal = $.trim(customInpKeyword.val());
						if(customKeyVal){
							tarMenu.attr("data-code",customKeyVal);
							tarMenu.attr("data-type",type);
							tarMenu.parent().children(".involAction").remove();
							_closeDialog();
						}else{ //如果没输入关键字
							alert("请输入自定义关键字");
						}
					}else if(custom == "link"){ //如果选中自定义链接  符必须符合链接格式
						customInpLink = $("#customInp-link");
						coustomLinkVal = $.trim(customInpLink.val());
						if(coustomLinkVal && coustomLinkVal !== "http://"){
							if(coustomLinkVal.indexOf("http://") == 0 || coustomLinkVal.indexOf("https://") == 0){
								tarMenu.attr("data-code",coustomLinkVal);
								tarMenu.attr("data-type",type);
								tarMenu.attr("data-custom",custom);
								tarMenu.parent().children(".involAction").remove();
								_closeDialog();
							}else{
								alert("自定义链接请以http://或https://开头");
							}
						}else{
							alert("请输入自定义链接");
						}
					}else{ //系统类型的action
						if(selectedRadio.length){
							code = selectedRadio.attr("data-code");
							tarMenu.attr("data-code",code);
							tarMenu.attr("data-type",type);
							tarMenu.attr("data-name",name);
							tarMenu.attr("data-custom",custom);
							tarMenu.val(name);
							tarMenu.parent().children(".involAction").remove();
						}
						_closeDialog();
					}
				})
				dialogContainer.attr("data-init","true");
			}
			if(ajaxSuccess !== "true"){
				ajaxGetAction({
					loading : function(){
						$("#gDialog-menuListUl").html('<p class="action-loading" style="width:100%; height:150px; line-height:150px; text-align:center">正在加载设置项，请稍后...</p>')
					},
					removeLoading : function(){
						$("#gDialog-menuListUl").html();
					},
					success : function(res){
						dialogContainer.attr("data-ajaxsuccess","true");
						var html = _buildAction(res.list);
						$("#gDialog-menuListUl").html(html);
						setTimeout(function(){
							matchAction(cur_type,cur_code);
						},10)
					},
					empty : function(res){},
					fail : function(res){},
					timeout : function(res){},
					error : function(res){}
				})
			}else{
				matchAction(cur_type,cur_code);
			}
		});
	}
	/**
	 * 为已设置菜单动作的菜单重新设置动作时，弹出dialog时自动match到该action
	 * @param type
	 * @param code
	 * @param custom  弃用
	 */
	function matchAction(type,code){
		$("#customInp-keyword").val("");
		$("#customInp-link").val("");
		$("#gDialog-body").find("input:radio").attr("checked",false);
		//暂时实现不了
		return false;
		$("#gDialog-body").find("input:radio").each(function(index,inp){
			var inp = $(this);
			var itype = inp.attr("data-type");
			var icode = inp.attr("data-code");
			if((type==itype) && (code==icode)){
				console.log("match")
				inp.attr("checked","checked");
				return false;
			}
		});
	}
	//保存菜单结构到服务器
	function onSubmitData(){
		var container = $("#menuTbody");
		var menus = container.find("input.textInp");
		var result = [];
		//保存前先校验是否符合提交
		menus.each(function(index,menu){
			var menu = $(this);
			var name = menu.val();
			var type = menu.attr("data-type");
			var code = menu.attr("data-code");
			var id = menu.attr("data-id");
			var pid = menu.attr("data-pid");
			var errMsg = [];
			if(!name) errMsg.push('<span class="errMsg involName">*请输入菜单名</span>');
			//如果是子菜单
			if(pid !== "-1" && code=="-1") errMsg.push('<span class="errMsg involAction">*请设置菜单动作</span>');
			//如果是父菜单
			if(pid == "-1"){
				var subMenus = menu.parent().next().children();
				if(subMenus.length == 0 && code=="-1"){ //如果父菜单没有下级子菜单，那么此父菜单必须设置菜单动作,如果它有子菜单，则不用为自己设置菜单动作
					errMsg.push('<span class="errMsg involAction">*请设置菜单动作</span>');
				}
			}
			menu.parent().children(".errMsg").remove();
			if(errMsg.length){
				menu.after($(errMsg.join(" ")));
			}else{
				result.push({
					pid : pid,
					id : id,
					name : name,
					type : type,
					code : code
				})
			}
		})
		//检查是否存在错误项
		if(container.find(".errMsg").length==0 && container.find(".involAction").length==0 && container.find(".involName").length==0){
			//校验通过开始提交
			ajaxSubmitMenuData({
				data : result,
				loading : function(){
					$("#menuLoadingLayer").show();
				},
				removeLoading : function(){
					$("#menuLoadingLayer").hide();
				},
				success : function(res){
					WXB.G.Alert("success",'<p style="wdith:160px">保存成功！</p>');
					$("#menuTbody").html("");
					ininRender(result);
				},
				fail : function(msg){
					alert(msg)
				}
			})
		}
	}
	//ajax取得setAction项
	function ajaxGetAction(config){
		var fn = new Function;
		var config = config || {};
		var loading = config.loading || fn;
		var removeLoading = config.removeLoading || fn;
		var success = config.success || fn;
		var empty = config.empty || fn;
		var fail = config.fail || fn;
		var timeout = config.timeout || fn;
		var error = config.error || fn;
		var hash = WXB.G.SwitchAccount.getHash();
		$.ajax({
			url : AJAX_URL,
			type : "GET",
			dataType : "JSON",
			timeout : AJAX_TIMEOUT,
			data : { action : "GetExistAction",hash:hash },
			beforeSend : function(){loading()},
			success : function(res){
				removeLoading();
				if(res.status=="ok"){
					if(res.list && res.list.length){
						success(res);
					}else{
						empty();
					}
				}else{
					fail(res.msg);
				}
			},
			error : function(xhr,txt){
				removeLoading();
				if(txt=="timeout"){
					timeout();
				}else{
					error();
				}
			}
		})
	}
	//ajax提交menu data
	function ajaxSubmitMenuData(config){
		var fn = new Function;
		var config = config || {};
		var loading = config.loading || fn;
		var removeLoading = config.removeLoading || fn;
		var success = config.success || fn;
		var fail = config.fail || fn;
		var timeout = config.timeout || fn;
		var error = config.error || fn;
		var data = config.data;
		var hash = WXB.G.SwitchAccount.getHash();
		var actype = WXB.G.SwitchAccount.getActype();
		if(Object.prototype.toString.call(data) !== "[object Array]"){
			console && console.log("数据格式不正确");
			return false;
		}
		$.ajax({
			url : AJAX_URL,
			type : "POST",
			dataType : "JSON",
			timeout : AJAX_TIMEOUT,
			data : { action : "CreateMenu",hash:hash, actype:actype, data:data },
			beforeSend : function(){loading()},
			success : function(res){
				removeLoading();
				if(res.status=="ok"){
					success(res);
				}else{
					fail(res.msg);
				}
			},
			error : function(xhr,txt){
				removeLoading();
				if(txt=="timeout"){
					timeout();
				}else{
					error();
				}
			}
		})
	}
	//初始化时父菜单是否可以设置action
	function watchParentSetAction(container){
		var container = $("#menuTbody");
		var childs = container.children();
		childs.each(function(index,container){
			var container = $(container)
			var subCon = container.find(".subMenuContainer");
			var setActionBtn = container.find(".parentmenu > .setParentActionBtn");
			if(subCon.children().length == 0){
				setActionBtn.removeClass("disabled");
			}else{
				setActionBtn.addClass("disabled");
			}
		})
	}

	//弹出设置层
	function _showDialog(callback){
		var mask = $("#gMaskLayer");
		mask.fadeIn();
		$("#gDialogContainer").animate({"top":30},"normal",function(){
			callback && callback();
		});
	}
	//关闭设置层
	function _closeDialog(callback){
		var mask = $("#gMaskLayer");
		var dialogContainer = $("#gDialogContainer");
		dialogContainer.animate({"top":"-1000px"});
		mask.fadeOut();
		callback && callback();
	}


	function matchUID(data){
		var id = 0;
		for(var i=0; i<data.length; i++){
			var _id = data[i].id;
			if(_id>id) id = _id;
		}
		UID.set(Number(id)+1);
	}

	function buildParentDom(data){
		var html = "";
		var id = data.id;
		var name = data.name;
		var textName = name == "-1" ? "" : name;
		var type = data.type;
		var code = data.code;
		var attr = 'data-pid="-1" data-id="'+id+'" data-name="'+name+'" data-type="'+type+'" data-code="'+code+'"';
		html += '<tr '+attr+' id="parentMenuContainer-'+id+'" class="hover parentMenuContainer">';
		html += '	<td style="border-top:none;">';
		html += '		<div class="parentmenu">';
		html += '			<input '+attr+' type="text" value="'+textName+'" class="form-control parentMenuInp textInp" style="display:inline-block;width:300px;">';
		html += '           <a '+attr+' class="setParentActionBtn" href="javascript:;" style="border-left:0 none"><i class="fa fa-pencil"></i> 设置此菜单动作</a>';
		html += '			<a '+attr+' class="addSubMenuBtn" href="javascript:;" title="添加子菜单"><i class="fa fa-plus"></i> 添加子菜单</a>';
		html += '			<a '+attr+' class="removeParentMenuBtn" href="javascript:;"><i class="fa fa-remove"></i> 删除此菜单</a>';
		html += '		</div>';
		html += '       <div data-pid="'+id+'" id="subMenuContainer-'+id+'" class="subMenuContainer" class="designer sonmenu"></div>';
		html += '	</td>';
		html += '</tr>';
		return html;
	}
	function buildSubDom(dataArr){
		var html = "";
		for(var i in dataArr){
			var data = dataArr[i];
			var id = data.id;
			var pid = data.pid;
			var name = data.name;
			var textName = name == "-1" ? "" : name;
			var type = data.type;
			var code = data.code;
			var attr = 'data-pid="'+pid+'" data-id="'+id+'" data-name="'+name+'" data-type="'+type+'" data-code="'+code+'"';
			html += '<div '+attr+' class="subMenuCon">';
			html += ' <input '+attr+' type="text" value="'+textName+'" class="form-control subMenuInp textInp" style="display:inline-block;width:220px;">';
			html += ' <a '+attr+' class="setSubActionBtn" href="javascript:;" style="border-left:0 none"><i class="fa fa-pencil"></i> 设置此菜单动作</a>';
			html += ' <a '+attr+' class="removeSubMenuBtn" href="javascript:;"><i class="fa fa-remove"></i> 删除此菜单</a>';
			html += '</div>';
		}
		return html;
	}



	return {setUp:setUp}


})